const Koa = require('koa');
const Router = require('koa-router');
const cors = require('@koa/cors');
const {koaBody} = require('koa-body');
const json = require('koa-json');
const app = new Koa();
const router = new Router();

// 所有的接口都要加/api才能请求
router.prefix('/api');

router.get('/',ctx=>{
    console.log(ctx)
    console.log(ctx.request)
    ctx.body = 'Hello World';
})

router.get('/api',ctx=>{
    const params = ctx.request.query
    console.log(params)
    console.log(params.name,params.age)
    ctx.body = {
        name:params.name,
        age:params.age
    };


})


router.get('/async',async(ctx)=>{
    let result = await new Promise((resolve)=>{
        setTimeout(()=>{
            resolve('Hello World 2s last')
        },2000)
    })
    ctx.body = result;
})

router.post('/post',async(ctx)=>{
    let {body} = ctx.request
    console.log(body)
    console.log(ctx.request)
    ctx.body = {
        ...body
    }
})

app.use(koaBody())
app.use(cors())
app.use(router.routes())
app.use(json({pretty: false, param: 'pretty'}))
    .use(router.allowedMethods())
app.listen(3001);